<script setup>
import { computed } from 'vue'
import { useCanvasStore } from '@/stores/canvas'
import { getComponentTemplate } from '@/config/components'

const canvasStore = useCanvasStore()

// 计算属性
const selectedComponent = computed(() => canvasStore.selectedComponent)
const selectedComponents = computed(() => canvasStore.selectedComponents)
const hasSelection = computed(() => selectedComponents.value.length > 0)
const hasMultipleSelection = computed(() => selectedComponents.value.length > 1)

// 获取组件模板配置
const componentTemplate = computed(() => {
    if (!selectedComponent.value) return null
    return getComponentTemplate(selectedComponent.value.type)
})

// 获取属性配置
const propConfigs = computed(() => {
    return componentTemplate.value?.propConfigs || {}
})

// 更新组件属性
const updateComponentProps = (key, value) => {
    if (!selectedComponent.value) return

    const newProps = { ...selectedComponent.value.props, [key]: value }
    canvasStore.updateComponent(selectedComponent.value.id, { props: newProps })
}

// 更新组件样式
const updateComponentStyle = (key, value) => {
    if (!selectedComponent.value) return

    const newStyle = { ...selectedComponent.value.style, [key]: value }
    canvasStore.updateComponent(selectedComponent.value.id, { style: newStyle })
}

// 更新API配置
const updateApiConfig = (eventType, config) => {
    if (!selectedComponent.value) return

    const newEvents = {
        ...selectedComponent.value.events,
        [eventType]: config
    }
    canvasStore.updateComponent(selectedComponent.value.id, { events: newEvents })
}

// 删除选中组件
const deleteComponents = () => {
    if (selectedComponents.value.length > 0) {
        canvasStore.removeSelectedComponents()
    }
}

// 处理选项数据（用于options类型）
const getOptionsValue = (options) => {
    if (!Array.isArray(options)) return []
    return options
}

const updateOptions = (newOptions) => {
    updateComponentProps('options', newOptions)
}

const addOption = () => {
    const currentOptions = getOptionsValue(selectedComponent.value?.props.options)
    const newOptions = [
        ...currentOptions,
        { label: `选项${currentOptions.length + 1}`, value: `option${currentOptions.length + 1}` }
    ]
    updateOptions(newOptions)
}

const removeOption = (index) => {
    const currentOptions = getOptionsValue(selectedComponent.value?.props.options)
    const newOptions = currentOptions.filter((_, i) => i !== index)
    updateOptions(newOptions)
}

const updateOption = (index, field, value) => {
    const currentOptions = getOptionsValue(selectedComponent.value?.props.options)
    const newOptions = [...currentOptions]
    newOptions[index][field] = value
    updateOptions(newOptions)
}

// 渲染不同类型的表单控件
const renderFormControl = (propKey, propConfig, currentValue) => {
    switch (propConfig.type) {
        case 'string':
        case 'url':
            return {
                component: 'a-input',
                props: {
                    value: currentValue || '',
                    placeholder: propConfig.placeholder,
                    size: 'small'
                },
                events: {
                    change: (e) => updateComponentProps(propKey, e.target.value)
                }
            }

        case 'textarea':
            return {
                component: 'a-textarea',
                props: {
                    value: currentValue || '',
                    placeholder: propConfig.placeholder,
                    rows: propConfig.rows || 3,
                    size: 'small'
                },
                events: {
                    change: (e) => updateComponentProps(propKey, e.target.value)
                }
            }

        case 'number':
            return {
                component: 'a-input-number',
                props: {
                    value: currentValue,
                    min: propConfig.min,
                    max: propConfig.max,
                    step: propConfig.step,
                    placeholder: propConfig.placeholder,
                    size: 'small',
                    class: 'w-full'
                },
                events: {
                    change: (value) => updateComponentProps(propKey, value)
                }
            }

        case 'boolean':
            return {
                component: 'a-checkbox',
                props: {
                    checked: !!currentValue
                },
                events: {
                    change: (e) => updateComponentProps(propKey, e.target.checked)
                }
            }

        case 'select':
            return {
                component: 'a-select',
                props: {
                    value: currentValue,
                    options: propConfig.options,
                    size: 'small',
                    class: 'w-full'
                },
                events: {
                    change: (value) => updateComponentProps(propKey, value)
                }
            }

        case 'color':
            return {
                component: 'a-input',
                props: {
                    value: currentValue || '#000000',
                    type: 'color',
                    size: 'small',
                    style: { width: '60px', height: '32px' }
                },
                events: {
                    change: (e) => updateComponentProps(propKey, e.target.value)
                }
            }

        default:
            return null
    }
}
</script>

<template>
    <div class="property-panel h-full flex flex-col">
        <!-- 属性面板标题 -->
        <div class="p-4 border-b border-gray-200">
            <h2 class="text-sm font-medium text-gray-800">属性面板</h2>
        </div>

        <!-- 无选中组件时的提示 -->
        <div v-if="!hasSelection" class="flex-1 flex items-center justify-center text-gray-400">
            <div class="text-center">
                <div class="text-4xl mb-2">⚙️</div>
                <div class="text-sm">选择组件以编辑属性</div>
            </div>
        </div>

        <!-- 多选时的提示 -->
        <div v-else-if="hasMultipleSelection" class="flex-1 p-4">
            <div class="bg-blue-50 p-3 rounded-lg mb-4">
                <div class="text-xs text-blue-600 mb-1">多选模式</div>
                <div class="text-sm font-medium">已选中 {{ selectedComponents.length }} 个组件</div>
            </div>

            <div class="space-y-2">
                <div v-for="component in selectedComponents" :key="component.id"
                    class="flex items-center justify-between p-2 bg-gray-50 rounded">
                    <span class="text-sm">{{ getComponentTemplate(component.type)?.name || component.type }}</span>
                    <span class="text-xs text-gray-500">{{ component.id.slice(0, 8) }}...</span>
                </div>
            </div>

            <!-- 多选操作 -->
            <div class="mt-4 pt-4 border-t border-gray-200">
                <a-popconfirm title="确定要删除这些组件吗？" @confirm="deleteComponents" ok-text="确定" cancel-text="取消">
                    <a-button danger size="small" block>
                        🗑️ 删除选中组件 ({{ selectedComponents.length }})
                    </a-button>
                </a-popconfirm>
            </div>
        </div>

        <!-- 有选中组件时显示属性 -->
        <div v-else class="flex-1 overflow-y-auto">
            <div class="p-4 space-y-4">
                <!-- 组件基本信息 -->
                <div class="bg-gray-50 p-3 rounded-lg">
                    <div class="text-xs text-gray-500 mb-1">组件信息</div>
                    <div class="text-sm font-medium">{{ componentTemplate?.name || selectedComponent.type }}</div>
                    <div class="text-xs text-gray-400">ID: {{ selectedComponent.id }}</div>
                </div>

                <!-- 动态属性面板 -->
                <a-collapse size="small" :bordered="false" :default-active-key="['basic']">
                    <a-collapse-panel key="basic" header="基本属性">
                        <div class="space-y-3">
                            <!-- 动态渲染属性控件 -->
                            <div v-for="(propConfig, propKey) in propConfigs" :key="propKey" class="form-item">
                                <label class="block text-xs text-gray-600 mb-1">
                                    {{ propConfig.label }}
                                </label>

                                <!-- 特殊处理options类型 -->
                                <div v-if="propConfig.type === 'options'" class="space-y-2">
                                    <div class="flex items-center justify-between">
                                        <span class="text-xs text-gray-500">选项配置</span>
                                        <a-button size="small" @click="addOption">+ 添加</a-button>
                                    </div>
                                    <div v-for="(option, index) in getOptionsValue(selectedComponent.props[propKey])"
                                        :key="index" class="p-2 border border-gray-200 rounded">
                                        <div class="flex space-x-2">
                                            <a-input :value="option.label"
                                                @change="e => updateOption(index, 'label', e.target.value)"
                                                placeholder="选项标签" size="small" />
                                            <a-input :value="option.value"
                                                @change="e => updateOption(index, 'value', e.target.value)"
                                                placeholder="选项值" size="small" />
                                            <a-button size="small" danger @click="removeOption(index)">
                                                删除
                                            </a-button>
                                        </div>
                                    </div>
                                </div>

                                <!-- 其他类型的控件 -->
                                <component v-else
                                    :is="renderFormControl(propKey, propConfig, selectedComponent.props[propKey])?.component"
                                    v-bind="renderFormControl(propKey, propConfig, selectedComponent.props[propKey])?.props"
                                    v-on="renderFormControl(propKey, propConfig, selectedComponent.props[propKey])?.events">
                                    <template v-if="propConfig.type === 'boolean'">
                                        {{ propConfig.label }}
                                    </template>
                                </component>
                            </div>
                        </div>
                    </a-collapse-panel>

                    <!-- 样式属性 -->
                    <a-collapse-panel key="style" header="样式属性">
                        <div class="space-y-3">
                            <div class="grid grid-cols-2 gap-2">
                                <div>
                                    <label class="block text-xs text-gray-600 mb-1">宽度</label>
                                    <a-input :value="selectedComponent.style?.width || ''"
                                        @change="e => updateComponentStyle('width', e.target.value)" size="small"
                                        placeholder="如: 200px" />
                                </div>
                                <div>
                                    <label class="block text-xs text-gray-600 mb-1">高度</label>
                                    <a-input :value="selectedComponent.style?.height || ''"
                                        @change="e => updateComponentStyle('height', e.target.value)" size="small"
                                        placeholder="如: 32px" />
                                </div>
                            </div>

                            <div v-if="selectedComponent.style?.backgroundColor !== undefined">
                                <label class="block text-xs text-gray-600 mb-1">背景色</label>
                                <a-input :value="selectedComponent.style.backgroundColor"
                                    @change="e => updateComponentStyle('backgroundColor', e.target.value)" size="small"
                                    type="color" />
                            </div>

                            <div v-if="selectedComponent.style?.border !== undefined">
                                <label class="block text-xs text-gray-600 mb-1">边框</label>
                                <a-input :value="selectedComponent.style.border"
                                    @change="e => updateComponentStyle('border', e.target.value)" size="small"
                                    placeholder="如: 1px solid #ccc" />
                            </div>
                        </div>
                    </a-collapse-panel>

                    <!-- 事件配置 -->
                    <a-collapse-panel key="events" header="事件配置">
                        <div class="space-y-4">
                            <!-- 点击事件配置 -->
                            <div v-if="['button'].includes(selectedComponent.type)">
                                <label class="block text-xs text-gray-600 mb-2">点击事件 (onClick)</label>
                                <div class="space-y-2">
                                    <a-select :value="selectedComponent.events?.onClick?.method || 'GET'"
                                        @change="value => updateApiConfig('onClick', { ...selectedComponent.events?.onClick, method: value })"
                                        size="small" class="w-full" placeholder="请求方法">
                                        <a-select-option value="GET">GET</a-select-option>
                                        <a-select-option value="POST">POST</a-select-option>
                                        <a-select-option value="PUT">PUT</a-select-option>
                                        <a-select-option value="DELETE">DELETE</a-select-option>
                                    </a-select>

                                    <a-input :value="selectedComponent.events?.onClick?.url || ''"
                                        @change="e => updateApiConfig('onClick', { ...selectedComponent.events?.onClick, url: e.target.value })"
                                        placeholder="API地址" size="small" />

                                    <a-textarea
                                        :value="JSON.stringify(selectedComponent.events?.onClick?.headers || {}, null, 2)"
                                        @change="e => {
                                            try {
                                                const headers = JSON.parse(e.target.value || '{}')
                                                updateApiConfig('onClick', { ...selectedComponent.events?.onClick, headers })
                                            } catch (err) { }
                                        }" placeholder="请求头 (JSON格式)" :rows="3" size="small" />

                                    <a-textarea
                                        :value="JSON.stringify(selectedComponent.events?.onClick?.body || {}, null, 2)"
                                        @change="e => {
                                            try {
                                                const body = JSON.parse(e.target.value || '{}')
                                                updateApiConfig('onClick', { ...selectedComponent.events?.onClick, body })
                                            } catch (err) { }
                                        }" placeholder="请求体 (JSON格式)" :rows="3" size="small" />
                                </div>
                            </div>

                            <!-- 变化事件配置 -->
                            <div
                                v-if="['input', 'number-input', 'select', 'radio-group', 'checkbox-group'].includes(selectedComponent.type)">
                                <label class="block text-xs text-gray-600 mb-2">变化事件 (onChange)</label>
                                <div class="space-y-2">
                                    <a-select :value="selectedComponent.events?.onChange?.method || 'GET'"
                                        @change="value => updateApiConfig('onChange', { ...selectedComponent.events?.onChange, method: value })"
                                        size="small" class="w-full" placeholder="请求方法">
                                        <a-select-option value="GET">GET</a-select-option>
                                        <a-select-option value="POST">POST</a-select-option>
                                        <a-select-option value="PUT">PUT</a-select-option>
                                        <a-select-option value="DELETE">DELETE</a-select-option>
                                    </a-select>

                                    <a-input :value="selectedComponent.events?.onChange?.url || ''"
                                        @change="e => updateApiConfig('onChange', { ...selectedComponent.events?.onChange, url: e.target.value })"
                                        placeholder="API地址" size="small" />
                                </div>
                            </div>
                        </div>
                    </a-collapse-panel>
                </a-collapse>

                <!-- 删除组件按钮 -->
                <div class="pt-4 border-t border-gray-200">
                    <a-popconfirm title="确定要删除这个组件吗？" @confirm="deleteComponents" ok-text="确定" cancel-text="取消">
                        <a-button danger size="small" block>
                            🗑️ 删除组件
                        </a-button>
                    </a-popconfirm>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
.property-panel {
    font-size: 13px;
}

.property-panel :deep(.ant-collapse-header) {
    padding: 8px 12px !important;
    font-size: 12px !important;
}

.property-panel :deep(.ant-collapse-content-box) {
    padding: 8px 12px !important;
}

.form-item {
    border-bottom: 1px solid #f0f0f0;
    padding-bottom: 12px;
}

.form-item:last-child {
    border-bottom: none;
    padding-bottom: 0;
}
</style>